package com.dhh.activity;

import greendroid.app.GDActivity;
import greendroid.widget.ActionBarItem.Type;

import java.util.ArrayList;
import java.util.List;

import com.dhh.R;
import com.dhh.dao.DataBaseHelper;
import com.dhh.util.Constant;
import com.dhh.util.StringUtil;
import com.dhh.util.manager.DietManager;
import com.dhh.util.manager.PlanManager;
import com.dhh.vo.FoodDiet;
import com.dhh.vo.FoodPlan;
import com.dhh.vo.PlanItem;
import com.dhh.widget.AmazingAdapter;
import com.dhh.widget.AmazingListView;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class DietDesignActivity extends GDActivity{	
	private DataBaseHelper db;
	private PlanManager pManager;
	private DietManager dManager;
	private AmazingListView lsComposer;
	private FoodPlan plan;
	private FoodDiet diet;
	private String cItemId;
	
	@Override
    public void onCreate(Bundle intent){
        super.onCreate(intent);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setActionBarContentView(R.layout.make_plan);
        
        db = new DataBaseHelper(getBaseContext());
        db.openDataBase();
        pManager = new PlanManager(db); 
        dManager = new DietManager(db); 
        
        getActionBar().setTitle("Design My Diet");
        getActionBar().setBackgroundColor(Color.rgb(14, 166, 249));
        getActionBar().getChildAt(0).
        	setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(DietDesignActivity.this,HomeActivity.class);	
					startActivity(intent);
				}}); 
        addActionBarItem(Type.Add).getItemView()
        .setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(DietDesignActivity.this,FoodAddActivity.class);
				intent.putExtra(Constant.FROM_ACTIVITY, Constant.FA_FOOD_DESIGN);
				intent.putExtra(Constant.C_DIET_ID, diet.getId());
				DietDesignActivity.this.startActivity(intent);
			}}); 
        lsComposer = (AmazingListView) findViewById(R.id.lsComposer);
		lsComposer.setDivider( null );
		lsComposer.setDividerHeight(1); 
		lsComposer.setPinnedHeaderView(LayoutInflater.from(this).inflate(R.layout.fp_items, lsComposer, false));
		lsComposer.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {				
				cItemId = ((TextView) view.findViewById(R.id.fp_item_id)).getText().toString();
				DietDesignActivity.this.showDialog(0);				
				return true;
			}
		});
  	}
	
	@Override
	public void onStart() {
        super.onStart();
		fillData();		
    }
	private void fillData(){
		plan = pManager.getCurrentPlanSimple();
		String did = getIntent().getStringExtra(Constant.C_DIET_ID);
		diet = dManager.getDiet(did);
		diet.initCurentCount();
		lsComposer.setAdapter(new SectionComposerAdapter());
		
		((TextView)findViewById(R.id.mp_plan_grain_c)).setText(diet.getCurrentGrain());
		((TextView)findViewById(R.id.mp_plan_fruit_c)).setText(diet.getCurrentFruit());
		((TextView)findViewById(R.id.mp_plan_vegetable_c)).setText(diet.getCurrentVegetable());
		((TextView)findViewById(R.id.mp_plan_dairy_c)).setText(diet.getCurrentDairy());
		((TextView)findViewById(R.id.mp_plan_protein_c)).setText(diet.getCurrentProteinFood());
		
		((TextView)findViewById(R.id.mp_plan_energy_t)).setText(plan.getEnergy());
		((TextView)findViewById(R.id.mp_plan_energy_c)).setText(diet.getCurrentEnergy());
	}
	
	@Override
    public void onResume(){
    	super.onResume();
        db.openDataBase();       
    }
    
    @Override
	protected void onPause(){
		super.onPause();
		if (db != null) {
			db.close();
		}
	}
    
    @Override
	protected void onStop(){
		super.onStop();
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch(id){
		case 0:
			return new AlertDialog.Builder(this)
			.setIcon(android.R.drawable.ic_dialog_alert)
			.setTitle("Are you sure you want to delete this food?")
			.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,	int whichButton){
						pManager.removePlanItem(cItemId);
						DietDesignActivity.this.fillData();
						Toast.makeText(getBaseContext(),"The food has been deleted!", Toast.LENGTH_SHORT).show();
					}
				}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,int whichButton){}
					}).create();
		}
		
		return null;
	}
		
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<Pair<String, List<PlanItem>>>  getAllData(){
		List<Pair<String, List<PlanItem>>>  lst = new ArrayList<Pair<String, List<PlanItem>>>();
		Pair bPair = new Pair(PlanItem.PERIOD_BREAKFAST,diet.getBreakFast());
		Pair lPair = new Pair(PlanItem.PERIOD_LUNCH,diet.getLunch());
		Pair dPair = new Pair(PlanItem.PERIOD_DINNER,diet.getDinner());
		Pair daPair = new Pair(PlanItem.PERIOD_SNACK,diet.getSnack());
		lst.add(bPair);
		lst.add(lPair);
		lst.add(dPair);
		lst.add(daPair);
		return lst;
	}
	
	public void onClickInListView(View v){
		LinearLayout layout = (LinearLayout) v.getParent();
		cItemId = ((TextView) layout.findViewById(R.id.fp_item_id)).getText().toString();
		DietDesignActivity.this.showDialog(0);
	}

	class SectionComposerAdapter extends AmazingAdapter {
		List<Pair<String, List<PlanItem>>> all = getAllData();

		@Override
		public int getCount() {
			int res = 0;
			for (int i = 0; i < all.size(); i++) {
				res += all.get(i).second.size();
			}
			return res;
		}

		@Override
		public PlanItem getItem(int position) {
			int c = 0;
			for (int i = 0; i < all.size(); i++) {
				if (position >= c && position < c + all.get(i).second.size()) {
					return all.get(i).second.get(position - c);
				}
				c += all.get(i).second.size();
			}
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		protected void onNextPageRequested(int page) {
		}

		@Override
		protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
			if (displaySectionHeader) {
				view.findViewById(R.id.header).setVisibility(View.VISIBLE);
				TextView lSectionTitle = (TextView) view.findViewById(R.id.header);
				lSectionTitle.setText(getSections()[getSectionForPosition(position)]);
			} else {
				view.findViewById(R.id.header).setVisibility(View.GONE);
			}
		}

		@Override
		public View getAmazingView(int position, View convertView, ViewGroup parent) {
			View res = convertView;
			if (res == null) res = getLayoutInflater().inflate(R.layout.item_composer, null);
			TextView foodName = (TextView) res.findViewById(R.id.fp_foodname);
			TextView foodGroup = (TextView) res.findViewById(R.id.fp_foodgroup);
			TextView service = (TextView) res.findViewById(R.id.fp_service);
			TextView calorie = (TextView) res.findViewById(R.id.fp_calorie);
			TextView itemId = (TextView) res.findViewById(R.id.fp_item_id);
			
			PlanItem item = getItem(position);
			foodName.setText(StringUtil.cutString(item.getFoodName(),40));
			foodGroup.setText(item.getFoodGroup()+",");
			service.setText(item.getQuatity()+" g,");
			calorie.setText(item.getEnergy()+" cal");
			itemId.setText(item.getId());
			
			return res;
		}

		@Override
		public void configurePinnedHeader(View header, int position, int alpha) {
			TextView lSectionHeader = (TextView)header;
			lSectionHeader.setText(getSections()[getSectionForPosition(position)]);
			lSectionHeader.setBackgroundColor(alpha << 24 | (0xbbffbb));
			lSectionHeader.setTextColor(alpha << 24 | (0x000000));
		}

		@Override
		public int getPositionForSection(int section) {
			if (section < 0) section = 0;
			if (section >= all.size()) section = all.size() - 1;
			int c = 0;
			for (int i = 0; i < all.size(); i++) {
				if (section == i) { 
					return c;
				}
				c += all.get(i).second.size();
			}
			return 0;
		}

		@Override
		public int getSectionForPosition(int position) {
			int c = 0;
			for (int i = 0; i < all.size(); i++) {
				if (position >= c && position < c + all.get(i).second.size()) {
					return i;
				}
				c += all.get(i).second.size();
			}
			return -1;
		}

		@Override
		public String[] getSections() {
			String[] res = new String[all.size()];
			for (int i = 0; i < all.size(); i++) {
				res[i] = all.get(i).first;
			}
			return res;
		}
		
	}
}